package com.zbcbms.controller;

import com.alibaba.druid.util.StringUtils;
import com.zbcbms.entity.User;
import com.zbcbms.service.impl.UserServiceImpl;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;

import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author fengq
 */
public class AddUserController implements Initializable {

    @FXML
    private TextField addUsername;
    @FXML
    private TextField addUserNumber;
    @FXML
    private DatePicker addJoinTime;
    @FXML
    private ComboBox<String> addRole;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        List<String> snackList = Arrays.asList("系统管理员", "图书管理员","借阅者");
        ObservableList<String> obList = FXCollections.observableArrayList(snackList);
        addRole.setItems(obList);
        addRole.getSelectionModel().select(2);
    }

    @FXML
    public void addUserAction(){
        String username=addUsername.getText();
        String userNumber=addUserNumber.getText();
        String addTime = addJoinTime.getEditor().getText();
        String roleValue=addRole.getValue();
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(userNumber)||StringUtils.isEmpty(addTime)){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误提醒");
            alert.setContentText("参数不能为空！");
            alert.showAndWait();
        }else {
            try {
                Date joinTime = new SimpleDateFormat("yyyy-MM-dd").parse(addTime);
                User user = new User();
                user.setUserName(username);
                user.setPassword("123456");
                user.setUserNumber(userNumber);
                user.setJoinDate(joinTime);
                user.setRole(roleValue);
                Boolean aBoolean = new UserServiceImpl().saveOne(user);
                if (aBoolean){
                    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                    alert.setContentText("添加成功！");
                    alert.setTitle("成功提醒");
                    alert.showAndWait();
                    resetUserAction();
                }else {
                    Alert alert = new Alert(Alert.AlertType.WARNING);
                    alert.setContentText("添加失败！");
                    alert.showAndWait();
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    @FXML
    public void resetUserAction(){
        addUsername.setText("");
        addUserNumber.setText("");
        addJoinTime.getEditor().setText("");
        addRole.getSelectionModel().select(2);
    }

}
